"""
应用配置管理
"""
from pydantic_settings import BaseSettings
from typing import List
import os


class Settings(BaseSettings):
    """应用配置类"""
    
    # 基础配置
    APP_NAME: str = "校园视频孪生系统"
    VERSION: str = "1.0.0"
    API_PREFIX: str = "/api/v1"
    
    # 数据库配置
    DATABASE_URL: str = "sqlite:///./data/campus_twin.db"
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379/0"
    
    # WVP-Pro配置
    WVP_PRO_BASE_URL: str = "http://localhost:18080"
    WVP_PRO_API_KEY: str = ""
    
    # ZLMediaKit配置
    ZLM_BASE_URL: str = "http://localhost:18080"
    ZLM_SECRET: str = "035c73f7-bb6b-4889-a715-d9eb2d1925cc"
    
    # JWT配置
    SECRET_KEY: str = "your-secret-key-change-in-production"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    
    # CORS配置
    CORS_ORIGINS: List[str] = [
        "http://localhost:3000",
        "http://localhost:8080",
        "http://127.0.0.1:3000",
        "http://127.0.0.1:8080"
    ]
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "./logs/app.log"
    
    # AI配置
    AI_MODEL_PATH: str = "./models"
    GPU_MEMORY_LIMIT: str = "8GB"
    AI_MAX_WAIT_TIME: float = 5.0  # AI处理最大等待时间(秒)
    AI_MAX_WORKERS: int = 4  # AI处理最大工作线程数
    
    # 实时流处理配置
    MAX_CONCURRENT_STREAMS: int = 500
    STREAM_PROCESSING_FPS: int = 3
    STREAM_BUFFER_SIZE: int = 10
    STREAM_TIMEOUT_SECONDS: int = 30
    MAX_CONCURRENT_TASKS: int = 10
    
    # 文件存储配置
    UPLOAD_DIR: str = "./uploads"
    SNAPSHOT_DIR: str = "./uploads/snapshots"
    RECORD_DIR: str = "./uploads/records"
    MAX_FILE_SIZE: int = 100 * 1024 * 1024  # 100MB
    
    # 视频流配置
    BASE_URL: str = "http://localhost:8000"
    STREAM_CACHE_TTL: int = 300  # 流缓存时间(秒)
    MAX_CONCURRENT_STREAMS: int = 50  # 最大并发流数
    STREAM_TIMEOUT: int = 30  # 流超时时间(秒)
    
    # 视频处理配置
    VIDEO_PROCESSING_FPS: int = 3  # 默认处理帧率
    MAX_CAMERAS: int = 500  # 最大摄像头数量
    FRAME_BUFFER_SIZE: int = 100  # 帧缓冲区大小
    VIDEO_RECONNECT_ATTEMPTS: int = 3  # 重连尝试次数
    VIDEO_RECONNECT_DELAY: int = 5  # 重连延迟(秒)
    FRAME_EXTRACTION_TIMEOUT: int = 10  # 帧提取超时(秒)
    VIDEO_CODEC_PREFERENCE: List[str] = ["h264", "h265", "mjpeg"]  # 编解码器优先级
    
    # 实时流处理配置
    REAL_TIME_PROCESSING_ENABLED: bool = True  # 启用实时处理
    STREAM_PROCESSING_WORKERS: int = 10  # 流处理工作进程数
    CAMERAS_PER_WORKER: int = 50  # 每个工作进程处理的摄像头数量
    STREAM_HEALTH_CHECK_INTERVAL: int = 30  # 流健康检查间隔(秒)
    STREAM_RESTART_COOLDOWN: int = 60  # 流重启冷却时间(秒)
    MAX_PROCESSING_LATENCY: float = 2.0  # 最大处理延迟(秒)
    ADAPTIVE_FPS_ENABLED: bool = True  # 启用自适应帧率
    MIN_PROCESSING_FPS: int = 1  # 最小处理帧率
    MAX_PROCESSING_FPS: int = 10  # 最大处理帧率
    
    # AI算法配置
    DEFAULT_AI_ALGORITHMS: List[str] = [
        "behavior_analysis",
        "crowd_density",
        "waste_detection"
    ]  # 默认启用的AI算法
    AI_ALGORITHM_PRIORITY: dict = {
        "behavior_analysis": 1,
        "crowd_density": 2,
        "waste_detection": 3,
        "cleanliness_assessment": 4,
        "teaching_quality": 5,
        "classroom_quality": 6
    }  # AI算法优先级
    AI_BATCH_SIZE: int = 16  # AI批处理大小
    AI_PROCESSING_TIMEOUT: float = 5.0  # AI处理超时(秒)
    
    # 性能监控配置
    PERFORMANCE_MONITORING_ENABLED: bool = True  # 启用性能监控
    METRICS_COLLECTION_INTERVAL: int = 10  # 指标收集间隔(秒)
    PERFORMANCE_ALERT_THRESHOLD: dict = {
        "cpu_usage": 90.0,  # CPU使用率告警阈值(%)
        "memory_usage": 85.0,  # 内存使用率告警阈值(%)
        "gpu_usage": 95.0,  # GPU使用率告警阈值(%)
        "processing_latency": 3.0,  # 处理延迟告警阈值(秒)
        "frame_drop_rate": 10.0  # 丢帧率告警阈值(%)
    }
    PERFORMANCE_REPORT_INTERVAL: int = 300  # 性能报告生成间隔(秒)
    
    # 热更新配置
    CONFIG_HOT_RELOAD_ENABLED: bool = True  # 启用配置热更新
    CONFIG_VALIDATION_ENABLED: bool = True  # 启用配置验证
    CONFIG_BACKUP_ENABLED: bool = True  # 启用配置备份
    CONFIG_CHANGE_LOG_ENABLED: bool = True  # 启用配置变更日志
    
    # 缓存配置
    CACHE_TTL: int = 3600  # 缓存时间(秒)
    
    model_config = {
        "env_file": ".env",
        "case_sensitive": True
    }


# 创建全局配置实例
settings = Settings()


def get_settings() -> Settings:
    """获取配置实例"""
    return settings


# 确保必要的目录存在
os.makedirs("data", exist_ok=True)
os.makedirs("logs", exist_ok=True)
os.makedirs("models", exist_ok=True)
os.makedirs("uploads", exist_ok=True)
os.makedirs("uploads/snapshots", exist_ok=True)
os.makedirs("uploads/records", exist_ok=True)